import time
from flask import Flask
from flask import request
import utils
import random
import urllib
import paramiko

app = Flask(__name__)

global port
port = 0


@app.route('/container/build', methods=['GET', 'POST'])
def build():
    tag = request.args.get('tag')
    dockerfile = request.args.get('dockerfile')
    return utils.build(dockerfile, tag)


@app.route('/test', methods=['GET', 'POST'])
def test():
    tag = request.form.get('tag')
    dockerfile = request.form.get('dockerfile')
    dockerfile = urllib.unquote(dockerfile).decode('utf8')
    build_res = utils.build(dockerfile, tag)
    if build_res.find('Successfully built') == -1:
        return 'Build Failed. Build logs:\n' + build_res
    globals()['port'] = (globals()['port'] + 1) % 1000
    port = globals()['port'] + 18000
    id = utils.run(tag, 22, port)
    if id is None:
        return "Can't run your image."
    time.sleep(1)
    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect('localhost', port=port, username='root', password='docker')
        _, out, err = client.exec_command('cat answer')
    except:
        utils.stop(id)
        return "Can't ssh into the container."
    out = out.read()
    err = err.read()
    utils.stop(id)
    if len(err) > 0:
        return 'Failed to open or read file "answer"'
    else:
        return out

if __name__ == '__main__':
    # app.run('0.0.0.0', use_reloader=False, debug=True)
    app.run('0.0.0.0')
